//
//  YBGoodsLikeVC.m
//  WuyouTang
//
//  Created by YB007 on 2020/10/19.
//  Copyright © 2020 cat. All rights reserved.
//

#import "YBGoodsLikeVC.h"
#import "YBGoodsLikeCell.h"
#import "YBGoodsInfoVC.h"
#import "OutsideGoodsDetailVC.h"
#import "CommodityDetailVC.h"

@interface YBGoodsLikeVC ()<UITableViewDelegate,UITableViewDataSource>
{
    int _paging;
    BOOL _currentEditeState;
    NSMutableArray *_flagDel;
    NSMutableArray *_delCollectionGoods;
    BOOL _singleDel;
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;

@end

@implementation YBGoodsLikeVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self pullData];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text = YZMsg(@"我的收藏");
    self.view.backgroundColor = UIColor.whiteColor;
    self.dataArray = [NSMutableArray array];
    _paging = 1;
    
    _flagDel = [NSMutableArray array];
    _delCollectionGoods = [NSMutableArray array];
    _currentEditeState = NO;
    self.rightBtn.hidden = NO;
    [self.rightBtn setTitle:YZMsg(@"管理") forState:0];
    self.rightBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 6);
    [self.rightBtn setTitleColor:UIColor.blackColor forState:0];
    
    self.subNavi.backgroundColor =  UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    
    [self.view addSubview:self.tableView];
    
}
#pragma mark -
-(void)pullData {
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Shop.getGoodsCollect" Dic:@{@"p":@(_paging)} Suc:^(int code, id info, NSString *msg) {
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        if (code == 0) {
            NSArray *infoA = [NSArray arrayWithArray:info];
            if (_paging == 1) {
                [_dataArray removeAllObjects];
            }
            if (infoA.count <= 0) {
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            }else {
                [_dataArray addObjectsFromArray:infoA];
            }
            if (_dataArray.count <=0) {
                [PublicView showTextNoData:_tableView text1:@"" text2:YZMsg(@"暂无数据") centerY:0.8];
            }else {
                [PublicView hiddenTextNoData:_tableView];
            }
            [weakSelf resetDelFlag];
            _currentEditeState = NO;
            [_tableView reloadData];
        }else {
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
    }];
}
#pragma mark - UITableViewDelegate、UITableViewDataSource
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YBGoodsLikeCell *cell = [YBGoodsLikeCell cellWithTab:tableView index:indexPath];
    cell.dataDic = _dataArray[indexPath.row];
    
    cell.selectionStyle = 0;
    if (_currentEditeState == NO) {
        cell.flagWidth.constant = 0;
        cell.thumbLeft.constant = 0;
    }else {
        cell.flagWidth.constant = 18;
        cell.thumbLeft.constant = 8;
    }
    NSString *flagStr = _flagDel[indexPath.row];
    if ([flagStr isEqual:@"1"]) {
        cell.flagIV.image = [UIImage imageNamed:@"下一步"];
    }else {
        cell.flagIV.image = [UIImage imageNamed:@"编辑-圈圈"];
    }

    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *subDic = _dataArray[indexPath.row];
    if (_currentEditeState) {
        //编辑
        NSString *flagStr = _flagDel[indexPath.row];
        if ([flagStr isEqual:@"1"]) {
            //取消选中
            [_flagDel replaceObjectAtIndex:indexPath.row withObject:@"0"];
            [_delCollectionGoods removeObject:subDic];
        }else {
            //选中
            [_flagDel replaceObjectAtIndex:indexPath.row withObject:@"1"];
            [_delCollectionGoods addObject:subDic];
        }
        [self changeRigthTitle];
        [tableView reloadData];
    }else {
        //进详情
        [self goGoodsInfo:indexPath];
    }
    
}
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    YBWeakSelf;
    UITableViewRowAction *delAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:YZMsg(@"删除") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        //NSLog(@"====del");
        _singleDel = YES;
        NSDictionary *subDic = _dataArray[indexPath.row];
        [_delCollectionGoods addObject:subDic];
        [weakSelf showDelAlert];
    }];
    delAction.backgroundColor = Pink_Cor;
    return @[delAction];
}
-(void)goGoodsInfo:(NSIndexPath *)indexPath {
    NSDictionary *subDic = _dataArray[indexPath.row];
    
    [PublicObj checkGoodsExistenceWithID:minstr([subDic valueForKey:@"id"]) Existence:^(int code, NSString *msg) {
        if (code ==0) {
            if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
                OutsideGoodsDetailVC *detail = [[OutsideGoodsDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
//                detail.liveUid= _liveUid;
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

            }else{
                CommodityDetailVC *detail = [[CommodityDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
//                detail.backTags = @"shop";
//                detail.liveUid= _liveUid;
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

            }

        }else{
            [MBProgressHUD showError:msg];

        }
    }];

//    YBGoodsInfoVC *infoVC = [[YBGoodsInfoVC alloc]init];
//    infoVC.infoType = InfoEnterType_Collect;
//    infoVC.touserID = minstr([subDic valueForKey:@"uid"]);
//    infoVC.goodsID = minstr([subDic valueForKey:@"id"]);
//    [[YBBaseAppDelegate sharedAppDelegate]pushViewController: infoVC animated:YES];
}
-(void)changeRigthTitle {
    BOOL haveSelDel = [self seldelCollectionGoods];
    if (haveSelDel) {
        [self.rightBtn setTitle:YZMsg(@"删除") forState:0];
    }else {
        [self.rightBtn setTitle:YZMsg(@"管理") forState:0];
    }
}
-(void)resetDelFlag {
    [_flagDel removeAllObjects];
    for (int i=0; i<_dataArray.count; i++) {
        [_flagDel addObject:@"0"];
    }
    [_delCollectionGoods removeAllObjects];
    [self changeRigthTitle];
}
-(BOOL)seldelCollectionGoods {
    BOOL haveSelDel = NO;
    for (NSString *delFlag in _flagDel) {
        if ([delFlag isEqual:@"1"]) {
            haveSelDel = YES;
            break;
        }
    }
    return haveSelDel;
}
- (void)clickNaviRightBtn {
   
    BOOL haveSelDel = [self seldelCollectionGoods];
    if (haveSelDel) {
        _singleDel = NO;
        [self showDelAlert];
    }else {
        //没选中 就切换编辑状态
        _currentEditeState = !_currentEditeState;
        [_tableView reloadData];
    }
    
}
-(void)sureDelSelCollection {

    NSString *idStrs = @"";
    for (NSDictionary *delDic in _delCollectionGoods) {
        idStrs = [idStrs stringByAppendingFormat:@"%@,",[delDic valueForKey:@"id"]];
    }
    YBWeakSelf;
    if (idStrs.length > 1) {
        //去掉最后一个逗号
        idStrs = [idStrs substringToIndex:[idStrs length] - 1];
        [MBProgressHUD showMessage:@""];
        [WYNetworking postWithUrl:@"Shop.batchDelCollect" Dic:@{@"goodsids":idStrs} Suc:^(int code, id info, NSString *msg) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:msg];
            if (code == 0) {
                [_dataArray removeObjectsInArray:_delCollectionGoods];
                //删除成功后
                [weakSelf resetDelFlag];
                _currentEditeState = NO;
                if (_dataArray.count <=0) {
                    [PublicView showTextNoData:_tableView text1:@"" text2:YZMsg(@"暂无数据") centerY:0.8];
                }else {
                    [PublicView hiddenTextNoData:_tableView];
                }
                [_tableView reloadData];
            }
        } Fail:^(id fail) {
            [MBProgressHUD hideHUD];
        }];
    }
    
    
   
}
-(void)showDelAlert{
    YBWeakSelf;
    NSString *msg = _singleDel?YZMsg(@"确定删除该条记录?"):YZMsg(@"确定删除所选收藏?");
    NSDictionary *contentDic = @{@"title":@"",@"msg":msg,@"left":YZMsg(@"取消"),@"right":YZMsg(@"确定"),@"richImg":@""};
    [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        if (eventType == 1) {
            //删除
            [weakSelf sureDelSelCollection];
        }else {
            //取消
            [weakSelf resetDelFlag];
            _currentEditeState = NO;
            [_tableView reloadData];
        }
    }];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return !_currentEditeState;
}
#pragma mark - set/get
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,64+statusbarHeight, _window_width, _window_height - 64-statusbarHeight)style:UITableViewStylePlain];
        _tableView.delegate   = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = UIColor.whiteColor;
        YBWeakSelf;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _paging = 1;
            [weakSelf pullData];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            _paging +=1;
            [weakSelf pullData];
        }];
        
    }
    return _tableView;
}


@end
